#include "msgbusimpl.h"
#include "agent.h"
#include "broker.h"
#include "consumer.h"
#include "producer.h"

CMsgBusImpl::CMsgBusImpl(void)
{
}

CMsgBusImpl::~CMsgBusImpl(void)
{
    logi("CMessageBusImpl::~CMessageBusImpl");
}
HRESULT CMsgBusImpl::Init(IBase* pRot, IBase* pBase)
{
    rc_error(pRot != NULL, E_FAIL);
    return pRot->QueryInterface(IID_IRot, (void**)&m_pRot);
}
HRESULT CMsgBusImpl::Uninit()
{
    HRESULT hr = S_OK;

    return hr;
}
HRESULT CMsgBusImpl::Start(_pid_t pid, unsigned int type)
{
    HRESULT hr = S_OK;
    hr = m_pRot->GetObject(CLSID_CAsynFrame, IID_IAsynFrame, (IBase**)&m_pIAsynFrame);
    rc_error(hr == S_OK, E_FAIL);
    rc_error(m_pIAsynFrame.m_p != INULL, E_FAIL);
    return hr;
}
HRESULT CMsgBusImpl::Stop(unsigned int exit)
{
    HRESULT hr = S_OK;

    m_pIAsynFrame.dispose();
    return hr;
}
HRESULT CMsgBusImpl::CreateNode(NODE_CLASS cls, IBase** pBase)
{
    HRESULT hr = E_FAIL;

    if (IS_BROKER(cls)) {
        CBrokerImpl* p = ALLOC_NEW CBrokerImpl();
        rc_error(p != NULL, E_FAIL);

        hr = p->CreateSChannel(m_pRot);
        rc_error(hr == S_OK, E_FAIL);

        hr = p->OpenCChannel();
        rc_error(hr == S_OK, E_FAIL);

        return p->QueryInterface(IID_IBroker, (void**)pBase);
    } else if (IS_PRODUCER(cls)) {
        rc_error(m_pIAsynFrame.m_p != NULL, E_FAIL);

        CProducerImpl* p = ALLOC_NEW CProducerImpl();
        rc_error(p != NULL, E_FAIL);

        _lComPtr<ITcpSocket> pISocket;
        hr = m_pIAsynFrame->CreateIo(io_tcp_socket, (IBase**)&pISocket);
        rc_error(hr == S_OK, E_FAIL);

        hr = p->CreateCChannel(pISocket);
        rc_error(hr == S_OK, E_FAIL);

        return p->QueryInterface(IID_IProducer, (void**)pBase);
    } else if (IS_CONSUMER(cls)) {
        rc_error(m_pIAsynFrame.m_p != NULL, E_FAIL);

        CConsumerImpl* p = ALLOC_NEW CConsumerImpl();
        rc_error(p != NULL, E_FAIL);

        _lComPtr<ITcpSocket> pISocket;
        hr = m_pIAsynFrame->CreateIo(io_tcp_socket, (IBase**)&pISocket);
        rc_error(hr == S_OK, E_FAIL);

        hr = p->CreateCChannel(pISocket);
        rc_error(hr == S_OK, E_FAIL);

        return p->QueryInterface(IID_IConsumer, (void**)pBase);
    } else if (IS_AGENT(cls)) {
        CAgentImpl* p = ALLOC_NEW CAgentImpl();
        rc_error(p != NULL, E_FAIL);

        _lComPtr<ITcpSocket> pISocket;
        hr = m_pIAsynFrame->CreateIo(io_tcp_socket, (IBase**)&pISocket);
        rc_error(hr == S_OK, E_FAIL);

        hr = p->CreateCChannel(pISocket);
        rc_error(hr == S_OK, E_FAIL);

        return p->QueryInterface(IID_IAgent, (void**)pBase);
    } else if (IS_REQ(cls)) {
    } else if (IS_REP(cls)) {
    }

    return hr;
}
